<template>
  <div class="medium-container">
    <ListTab
      v-model="activeTabs"
      :show-header="!showMobilePage"
      :tabs="tabsList"
      is-table
      @tabClick="handleTabClick">
      <div slot="extendTabs">
        <!-- 直播&更多tab -->
        <ExtendTabs
          :live-platform-list="livePlatformList"
          :video-platform-list="videoPlatformList"
          :active-tabs="activeTabs"
          @tabsChange="handleExtendTabsChange"
        />
      </div>
    </ListTab>
    <div v-loading="listLoading" :class="{'mobile-min-height mobile-el-pagination':showMobilePage}" class="resource-content">
      <DataDisplay
        :data-list="statisticsList"
        class="mobile-data statistics-box"
        show-pointer
        @handleNumClick="dataSearch"
      />
      <div :class="{'filter-open': filterOpen && !showMobilePage}" class="resource-page-left">
        <div v-if="!showMobilePage" class="opeator-bar">
          <TableFilter
            ref="baseFilterRef"
            :filter-list="baseFilterList"
            v-model="paramsObj"
            :select-value-result="selectValueResult"
            :get-preset-filter="getPresetFilter"
            :preset-info="getPresetInfo()"
            is-show-config
            @deleteTag="filterOperate($event, 'deleteTag')"
            @handelClick="filterOperate($event,'queryClick')"
            @queryEmpty="filterOperate($event,'queryEmpty')"
            @setFilterParams="filterOperate($event,'setFilterParams')"
            @filterTagStatus="filterTagStatus"
          />
          <!-- <div v-if="resourceData.data" class="total-container">共有<span class="num">{{ resourceData.data.total }}</span>个账号</div> -->
          <span class="flex-one"/>
          <div class="flex-center">
            <viewPopover :all-view-data="allViewData" :cur-view="curView" @changeView="changeView" @freshData="getViewList">
              <div class="default-view flex-center">
                <div class="view-name flex-center">
                  <ToolTip :content="curView && curView.name || '默认视图'" />
                </div>
                <div class="view-icon flxe-center">
                  <img :src="editViewIcon" width="16" height="16" alt="" @click.stop="setTableCloumn">
                </div>
              </div>
            </viewPopover>
          </div>
          <createBtn v-if="hasRouteAuth('medium:operator:resourceAdd')" style="margin-left:12px;" @click.native="toCreate" />
          <MoreOpeator
            :list="[
              {label: '自定义指标', handelClick: setTableCloumn},
              {label: '模板下载', type: 'export', divided:hasRouteAuth('medium:operator:merge') || isShopCarAuth, auth: hasRouteAuth('medium:operator:templateDownload'), exportApi:'/admin/medium/template', exportName:'导入模板'},
              // {label: '导入', type: 'import', callback: getMediumData, auth: activeTabs !== '' && hasRouteAuth('medium:operator:import'), accept: '.xls,.xlsx', importApi: '/admin/medium/import', extendParams: { platformType: activeTabs }},
              {label: '导入新增(量大)', handelClick: goUpload, auth:hasRouteAuth('medium:operator:importAll'),tip:'判断平台、账号与账号ID是否一致对资源进行修改（可新增)'},
            ]"
            style="margin-left:12px;"
          >
            <ImportNExport
              ref="ImportNExport"
              :get-filter-params="getFilterParams"
              :extend-list="[
                {label:'导出', refName:'listExport', exportApi:'/admin/medium/exportAll', exportName:'资源列表', beforeExport: exportBeforeExport, isBeforeExport: true, type: 'export', httpMethod: 'post', auth: activeTabs === '' && hasRouteAuth('medium:operator:export')},
                {label:'导出', refName:'listExport', handelClick: exportExcelShow, auth: activeTabs !== '' && hasRouteAuth('medium:operator:export'), type: 'export' },
              ]"
              @getMediumData="getMediumData"/>
          </MoreOpeator>
        </div>
        <div class="table-list" style="min-height: 300px">
          <TableList
            v-if="!resourceData.isInit"
            ref="mediumListTabel"
            :tabs="tabs"
            :active-tabs="activeTabs"
            :table-list-setting="tableListSetting"
            :cur-view="curView"
            :resource-data="resourceData"
            :table-height="setTableHeight"
            :dynamic-key-list="dynamicKeyList"
            @toPage="toPage"
            @mergeShow="mergeShow"
            @quicklyCreate="quicklyCreate"
            @getMediumData="getMediumData"
            @sortMediumData="sortMediumData"
            @editInfoCallBack="editInfoCallBack"
            @mutedUpdateMediumList="mutedUpdateMediumList"
            @handleExportIds="handleExportIds"
          >
            <template v-if="showMobilePage" slot="mobile-footer">
              <div class="mobile-icon" @click="switchFilterOpen()">
                <el-image :src="mobileIcon" class="img"/>
                <span class="text">筛选</span>
              </div>
              <MoreOpeator
                :list="[
                  {label: '询单', auth: hasRouteAuth('crm:flyNotice:create'), handelClick: () => quicklyCreate('询单', 'flyNoticeCreate')},
                  {label: '询价', auth: hasRouteAuth('crm:flyPrice:create'), handelClick: () => quicklyCreate('询价', 'flyPriceCreate')},
                  {label: '模板下载', type: 'export', divided:hasRouteAuth('medium:operator:merge') || isShopCarAuth, auth: hasRouteAuth('medium:operator:templateDownload'), exportApi:'/admin/medium/template', exportName:'导入模板'},
                  // {label: '导入', type: 'import', callback: getMediumData, auth: activeTabs !== '' && hasRouteAuth('medium:operator:import'), accept: '.xls,.xlsx', importApi: '/admin/medium/import', extendParams: { platformType: activeTabs }},
                  {label: '导入新增(量大)', handelClick: goUpload, auth:hasRouteAuth('medium:operator:importAll'),tip:'判断平台、账号与账号ID是否一致对资源进行修改（可新增)'}
                ]"
                show-mobile-icon
              >
                <ImportNExport
                  ref="ImportNExport"
                  :get-filter-params="getFilterParams"
                  :extend-list="[
                    {label:'导出', refName:'listExport', exportApi:'/admin/medium/exportAll', exportName:'资源列表', beforeExport: exportBeforeExport, isBeforeExport: true, type: 'export', httpMethod: 'post', auth: activeTabs === '' && hasRouteAuth('medium:operator:export')},
                    {label:'导出', refName:'listExport', handelClick: exportExcelShow, auth: activeTabs !== '' && hasRouteAuth('medium:operator:export'), type: 'export' },
                  ]"
                  @getMediumData="getMediumData"
                />
              </MoreOpeator>
            </template>
            <createBtn v-if="showMobilePage && hasRouteAuth('medium:operator:resourceAdd')" slot="mobile-create" mobile-table @click.native="$router.push({name: 'createResource'})" />
          </TableList>
        </div>
      </div>
      <div :class="{'resource-page-right':!showMobilePage}">
        <ResourceFilter
          ref="filter"
          v-model="paramsObj"
          :active-tabs="activeTabs"
          :dynamic-key-list="dynamicKeyList"
          :select-value-result="selectValueResult"
          @setValueModelResult="setValueModelResult"
          @freshData="() => {getMediumData(true)}"
        />
      </div>
    </div>
    <mergeList ref="mergeListRef" @freshData="getMediumData" />
    <ExportExcel ref="exportExcelMaskRef" :tabs="allTabs" :active-tabs="activeTabs " />
    <TableSetting
      ref="tableSettingRef"
      :view-data="curView"
      :dynamic-key-list="dynamicKeyList"
      :platform="activeTabs"
      @freshViewList="getViewList"
      @resetList="resetSeting"
      @changeView="changeView"
      @handelSubmit="resetSeting" />
    <resourceDialog ref="resourceCreateRef" @success="getMediumData"/>
  </div>
</template>
<script>
import { getFilterList } from '@/api/medium';
import { getResourceListPost, getResourceEditAuth, resourceFilter, getStatisticsData } from '@/api/resource';
// components
import ResourceFilter from '@/components/resource/filter/resourceFilter';
import ImportNExport from '@/components/MediumPage/ImportNExport';
import ExportExcel from '@/components/MediumPage/ExportExcelMask';
import TableList from '@/components/resource/table/tableList'; // 表格
import mergeList from '@/components/resource/merge/mergeList';
import ListTab from '@/components/ListTab';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import ExtendTabs from './model/extendTabs';
import TableSetting from './model/tableSetting';
import TableFilter from '@/components/resource/filter/module/tableFilter';
import resourceDialog from '@/views/resource/components/resourceDialog';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import viewPopover from './model/viewPopover';
// utils
import { paramsAryToStr } from '@/utils/paramsFormat';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import opeatorFn from './mixins/opeatorFn';
import tableSettingMixins from './mixins/tableSetting';
import TableAdaptive from '@/mixins/tableAdaptive';
import { mapState } from 'vuex';
import axios from 'axios';
import mobileTable from '@/mixins/mobileTable';
import mobileIcon from '@/assets/mobileIcon/search.png';
import icon_54 from '@/assets/dataDisplay/icon_54.png';
import icon_55 from '@/assets/dataDisplay/icon_55.png';
import icon_56 from '@/assets/dataDisplay/icon_56.png';
import icon_57 from '@/assets/dataDisplay/icon_57.png';
import icon_58 from '@/assets/dataDisplay/icon_58.png';
import editViewIcon from '@/assets/edit-active.png';
export default {
  components: {
    TableList, ResourceFilter, createBtn, btnGroup, ExportExcel,
    ImportNExport, mergeList, ListTab, MoreOpeator, ExtendTabs,
    TableSetting, TableFilter, resourceDialog, DataDisplay, viewPopover
  },
  mixins: [opeatorFn, TableAdaptive, mobileTable, tableSettingMixins],
  data() {
    return {
      icon_54, icon_55, icon_56, icon_57, icon_58,
      mobileIcon, editViewIcon,
      paramsObj: {},
      paramsOptions: [],
      receiveListCancelToken: null,
      activeTabs: '',
      listLoading: false,
      expendStatus: 0,
      tabs: [
        { label: '全部', key: '', ziduan: 'all', authShow: true },
        { label: '微信', key: '1', ziduan: 'weixin', authShow: hasRouteAuth('medium:platform:weixin') },
        { label: '微博', key: '2', ziduan: 'weibo', authShow: hasRouteAuth('medium:platform:weibo') },
        { label: '小红书', key: '3', ziduan: 'xiaohongshu', authShow: hasRouteAuth('medium:platform:xiaohongshu') },
        { label: '抖音', key: '4', ziduan: 'douyin', authShow: hasRouteAuth('medium:platform:douyin') },
        { label: 'B站', key: '7', ziduan: 'bzhan', authShow: hasRouteAuth('medium:platform:bilibili') }
        // { label: '直播', key: '6', ziduan: 'zhibo', authShow: hasRouteAuth('medium:platform:live') },
        // { label: '更多', key: '5', ziduan: 'duanshipin', authShow: hasRouteAuth('medium:platform:video') }
      ],
      filterData: {},
      resourceData: {
        isInit: true
      },
      page: 1,
      perPage: 20,
      sortType: -1, // table排序
      sortName: '',
      realTimeFilter: false,
      filterDataCallback: null,
      isPageInit: true, // 是否第一次进入页面
      videoPlatformList: [],
      livePlatformList: [],
      dynamicKeyList: {}, // 自定义字段
      selectValueResult: [],
      statisticsList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'filterOpen': state => state.medium.filterOpen,
      'userAuthType': state => state.medium.userAuthType,
      'filterConfig': state => state.filter.filterConfig
    }),
    isShopCarAuth() {
      return this.userAuthType === 1 || this.userAuthType === 3;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 193 : 177;
    },
    tabsList() {
      const tabs = this.tabs;
      return tabs.filter(i => {
        i.name = i.label;
        i.id = i.key;
        return i.authShow;
      });
    },
    allTabs() {
      const extendTabs = [
        { label: '直播', key: '6', ziduan: 'zhibo', authShow: hasRouteAuth('medium:platform:live') },
        { label: '更多', key: '5', ziduan: 'duanshipin', authShow: hasRouteAuth('medium:platform:video') }
      ];
      return [...this.tabs, ...extendTabs];
    },
    presetFilter() { // 快捷筛选条件值的默认值
      const routeName = this.$route.name;
      if (!this.filterConfig || !this.filterConfig[routeName]) return null;
      const activeTabs = this.activeTabs || 'all';
      const defaultFilter = this.filterConfig[routeName].find(i => {
        return (!i.activeTabs || i.activeTabs === activeTabs) && i.default;
      });
      if (defaultFilter) return _.cloneDeep(defaultFilter);
      return null;
    },
    baseFilterList() {
      return [
        { keyword: 'resourceName', name: '账号', type: 'input', labelWidth: '70px' },
        { keyword: 'code', name: '账号ID', type: 'input', labelWidth: '70px' },
        { keyword: 'link', name: '链接', type: 'input', labelWidth: '70px' }
      ];
    }
  },
  created() {
    if (this.$route.params.checkInput) {
      this.activeTabs = this.$route.params.activeTabs;
      this.paramsOptions = this.$route.params.paramsOptions;
      this.paramsObj = {
        resourceName: this.$route.params.resourceName,
        link: this.$route.params.resourceLink,
        id: this.$route.params.resourceId
      };
    }
    if (this.$route.query.accountNames) {
      const data = {
        params: {
          filterModel: {
            accounts: this.$route.query.accountNames.replace(/\\n/g, '\n')
          },
          filterOptions: {}
        }
      };
      this.$nextTick(() => {
        this.$refs.filter.setFilterParams(data);
        this.getMediumData(true);
        this.$router.replace({
          name: 'resource'
        });
      });
    }
    if (this.$route.query.toCreate) {
      const { signUpId, accountId, supplier, supplierType, supplierId } = this.$route.query;
      this.$nextTick(() => {
        const params = {
          supplier,
          supplierId: Number(supplierId),
          supplierType: Number(supplierType)
        };
        this.toCreate(params);
        signUpId && accountId && this.getSignUpDetail(signUpId, accountId);
      });
    }
    if (this.$route.query.isFromNotice) {
      const data = {
        params: {
          filterModel: {
            journalStatus: 1,
            cooperationOption: 2,
            executeBroker: '#未配置#'
          },
          filterOptions: {}
        }
      };
      this.$nextTick(() => {
        this.$refs.filter.setFilterParams(data);
        this.getMediumData(true);
        this.$router.replace({
          name: 'resource'
        });
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editResource' || 'detailResource') {
      to.meta.isRedirectEdit = true;
    } else {
      to.meta.isRedirectEdit = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isRedirectEdit && this.resourceData.code === 200) {
      this.getMediumData();
    } else {
      const defaultTab = this.$route.query.platform;
      if (defaultTab) {
        const isDefaultTabAuth = this.allTabs.some(i => {
          return i.authShow && defaultTab.toString() === i.key.toString();
        });
        if (isDefaultTabAuth) this.activeTabs = defaultTab + '';
      } else {
        this.activeTabs = this.setActiveTabs();
      }
      this.paramsObj = {};
      this.perPage = 20;
      this.page = 1;
      if (this.$refs.mediumListTabel && this.$refs.mediumListTabel.clearMixinSelection) {
        this.$refs.mediumListTabel.clearMixinSelection();
      }
      // 跳转搜索
      const { type, label, operator, signExpireStartDate, signExpireEndDate, contractBroker, signDetailStatus, priceUpdateStartTime, priceUpdateEndTime } = this.$route.query;
      if (type) { this.getRouteQuery(); }
      if (label) { this.$set(this.paramsObj, 'tag', Number(this.$route.query.label)); }// 签约审批，标签搜索
      if (operator) { this.$set(this.paramsObj, 'operator', this.$route.query.operator); }
      if (signExpireStartDate || signExpireEndDate) { // 飞书通知跳转搜索
        this.$set(this.paramsObj, 'signExpireDate', [Number(signExpireStartDate), Number(signExpireEndDate)]);
        this.$set(this.paramsObj, 'contractBroker', contractBroker);
        if (signDetailStatus) {
          const status = signDetailStatus.split(',').map(i => Number(i));
          this.$set(this.paramsObj, 'signDetailStatus', status);
        }
      }
      if (priceUpdateStartTime || priceUpdateEndTime) { // 飞来询价价格更新通知
        this.$set(this.paramsObj, 'priceUpdateDate', [Number(priceUpdateStartTime), Number(priceUpdateEndTime)]);
        this.$set(this.paramsObj, 'contractBroker', contractBroker);
      }
      this.initMultipleTabs();
      this.getInit();
    }
  },
  methods: {
    hasRouteAuth,
    handleExportIds(val) {
      this.selectIds = val;
    },
    setActiveTabs() {
      let activeTabs = '';
      const tabs = this.allTabs;
      for (let i = 0; i < tabs.length; i++) {
        if (tabs[i].authShow) {
          activeTabs = tabs[i].key || '';
          return activeTabs;
        }
      }
      return activeTabs;
    },
    getFilterParams(isList = false) {
      return new Promise(async(resolve) => {
        await this.$nextTick();
        let paramsObj = {
          filterModel: {},
          options: [],
          priceOptions: []
        };
        if (this.$refs.filter) {
          paramsObj = this.$refs.filter.getFilterParams();
        }
        const journalPriceOptionsObj = paramsObj.priceOptions.filter(i => i.type === 0);
        const costPriceOptionsObj = paramsObj.priceOptions.filter(i => i.type === 1);
        const params = {
          ...paramsObj.filterModel,
          journalPriceOptionsObj,
          costPriceOptionsObj,
          page: this.page,
          perPage: this.perPage,
          platformType: this.activeTabs,
          sortType: this.sortType,
          sortName: this.sortName
        };
        params.optionsObj = [...paramsObj.options, ...this.paramsOptions];

        if (!isList) {
          params.ids = this.getResourceSelectedIds();
          params.idList = this.getResourceSelectedIds() ? this.getResourceSelectedIds().split(',') : [];
        }

        if (params.area) {
          params.area = params.area.join('-');
        }
        const rangeDateKeys = [{
          attr: 'cooperationTime',
          start: 'cooperationStart',
          end: 'cooperationEnd',
          addTime: true
        }, {
          attr: 'signDate',
          start: 'signStartDate',
          end: 'signEndDate',
          addTime: true
        }, {
          attr: 'signExpireDate',
          start: 'signExpireStartDate',
          end: 'signExpireEndDate',
          addTime: true
        }, {
          attr: 'priceUpdateDate',
          start: 'priceUpdateStartTime',
          end: 'priceUpdateEndTime',
          addTime: true
        }];
        paramsRangeFormat;
        const arrayKeyArr = ['departmentId', 'operateMode', 'tag', 'orderPlatformId',
          'signDetailStatus', 'queryTagName', 'cooperationFormId', 'departmentNames', 'signGroups', 'orderNum', 'cooperationOptions'];
        paramsRangeFormat(rangeDateKeys, params);
        paramsAryToStr(arrayKeyArr, params);
        resolve(params);
      });
    },
    // 初始化直播和更多tab的下拉项
    async initMultipleTabs() {
      this.videoPlatformList = await this.getAllPlatform(5) || []; // 更多
      this.livePlatformList = await this.getAllPlatform(6) || []; // 直播
    },
    async getAllPlatform(type) {
      const result = await getFilterList({ type }) || {};
      const options = result.data && result.data.options || [];
      let platformList = [];
      options.forEach(item => {
        if (item.key === 'pingtai') {
          (item.valueList || []).forEach(i => {
            i.name = i.label;
            i.id = i.key;
          });
          platformList = item.valueList || [];
        }
      });
      return platformList;
    },
    async getInit() {
      await this.getSettingData();
      if (this.presetFilter) {
        if (this.$refs.filter) {
          setTimeout(() => {
            this.$refs.filter.presetFilterDefault(this.presetFilter);
          }, 300);
        }
      } else {
        this.getMediumData(true);
      }
    },
    // 获取统计数据
    async getStatisticsData(paramsObj = {}) {
      try {
        const params = _.cloneDeep(paramsObj);
        const { page, perPage } = params;
        if (page) delete params.page;
        if (perPage) delete params.perPage;
        const res = await getStatisticsData(params);
        const { code, data = {}} = res;
        if (code === 200) {
          const { signed, journal, noJournal, cancelJournal, exclusiveAgency, noExclusiveAgency } = data;
          this.statisticsList = [
            { data: signed, keyword: 'signed', label: '已签约', tooltip: '签约状态为已签约（待签合同）、已签约（已签合同）、已签约（已续约）、已签约（自动续约）的账号', icon: icon_54, isMoney: false },
            { data: journal, keyword: 'journal', label: '已上刊', tooltip: '上刊状态为已签约-上刊的账号', icon: icon_55, isMoney: false },
            { data: noJournal, keyword: 'noJournal', label: '不上刊', tooltip: '上刊状态为已签约-不上刊的账号', icon: icon_56, isMoney: false },
            { data: cancelJournal, keyword: 'cancelJournal', label: '下刊', tooltip: '上刊状态为下刊的账号', icon: icon_57, isMoney: false },
            { data: exclusiveAgency, keyword: 'exclusiveAgency', label: '独家代理', tooltip: '运营模式为非飞博主体-独家代理的账号', icon: icon_58, isMoney: false },
            { data: noExclusiveAgency, keyword: 'noExclusiveAgency', label: '非独家代理', tooltip: '运营模式为非飞博主体-非独家代理的账号', icon: icon_58, isMoney: false }
          ];
        }
      } catch (error) {
        console.log(error);
        this.statisticsList = [
          { data: 0, keyword: 'signed', label: '已签约', tooltip: '签约状态为已签约（待签合同）、已签约（已签合同）、已签约（已续约）、已签约（自动续约）的账号', icon: icon_54, isMoney: false },
          { data: 0, keyword: 'journal', label: '已上刊', tooltip: '上刊状态为已签约-上刊的账号', icon: icon_55, isMoney: false },
          { data: 0, keyword: 'noJournal', label: '不上刊', tooltip: '上刊状态为已签约-不上刊的账号', icon: icon_56, isMoney: false },
          { data: 0, keyword: 'cancelJournal', label: '下刊', tooltip: '上刊状态为下刊的账号', icon: icon_57, isMoney: false },
          { data: 0, keyword: 'exclusiveAgency', label: '独家代理', tooltip: '运营模式为非飞博主体-独家代理的账号', icon: icon_58, isMoney: false },
          { data: 0, keyword: 'noExclusiveAgency', label: '非独家代理', tooltip: '运营模式为非飞博主体-非独家代理的账号', icon: icon_58, isMoney: false }
        ];
      }
    },
    getRouteQuery() { // 新建，同平台账号、链接搜索
      this.paramsObj = {
        code: this.$route.query.resourceId,
        resourceName: this.$route.query.resourceName,
        link: this.$route.query.resourceLink
      };
      this.activeTabs = this.$route.query.activeTabs;
      const fitPlatformType = [1, 2, 3, 4, 7];// 微信、微博、小红书、抖音、B站
      if (!fitPlatformType.includes(this.activeTabs)) {
        this.paramsObj.optionsObj = [{ key: 'pingtai', value: `${this.$route.query.platformType}` }];
      }
    },
    sortMediumData(params) {
      this.sortName = params.sortName;
      this.sortType = params.sortType;
      this.getMediumData();
    },
    // 获取媒介数据
    async getMediumData(reset = false, muted = false) {
      if (reset) { this.page = 1; }
      const paramsObj = await this.getFilterParams(true);
      if (paramsObj.createTime && paramsObj.createTime.length === 2) {
        paramsObj.createTimeStart = Math.floor(paramsObj.createTime[0] / 1000);
        paramsObj.createTimeEnd = Math.floor(paramsObj.createTime[1] / 1000);
      }
      this.getStatisticsData(paramsObj);
      if (!muted) this.listLoading = true;
      try {
        if (this.receiveListCancelToken) {
          this.receiveListCancelToken.cancel('cancel');
        }
        const source = axios.CancelToken.source();
        this.receiveListCancelToken = source;
        const result = await getResourceListPost(paramsObj, source.token);
        if (result.code === 200 && result.data) {
          const mediumIds = [];
          if (result.data.items) {
            result.data.items.forEach((i, index) => {
              i.isEditAuth = true;
              mediumIds.push(i.mediumId);
              i.$index = index;
              if (i.accountOperation && i.accountOperation.length > 0) {
                i.accountOperationName = i.accountOperation.map(j => j.value);
              }
              if (i.cooperationDepartment && i.cooperationDepartment.length > 0) {
                i.cooperationDepartmentNames = i.cooperationDepartment.map(j => j.value).join('/');
              }
            });
          }
          this.resourceData = result;
          this.resourceData.isInit = false;
          // 获取资源列表是否有编辑权限
          if (mediumIds.length > 0) {
            getResourceEditAuth({ ids: mediumIds }).then(authRes => {
              this.listLoading = false;
              if (authRes.code === 200 && authRes.data) {
                this.resourceData.data.items.forEach(i => {
                  i.isEditAuth = authRes.data[i.mediumId] || false;
                });
              }
            }).catch(() => {
              this.listLoading = false;
            });
            return;
          }
        }
        this.listLoading = false;
      } catch (error) {
        if (error.message !== 'cancel') this.listLoading = false;
      }
    },
    // 获取筛选列表
    async getFilter() {
      const filterParams = { type: this.activeTabs };
      const result = await getFilterList(filterParams);
      if (result.code === 200) {
        this.filterData = result;
        if (this.$route.query.label) {
          this.filterData.data.options.forEach(el => {
            if (el.label === '标签') {
              el.checkedList.push(this.$route.query.label);
            }
          });
        }
        const index = this.filterData.data.options.findIndex(item => {
          return item.label === '标签';
        });
        this.filterData.data.options.splice(index, 1);
        // 取消显示地域项（已调整为下拉筛选）
        this.filterData.data.options = this.filterData.data.options.filter(i => i.key !== 'address');
      }
      if (this.filterDataCallback) this.filterDataCallback();
      return result;
    },
    // 筛选条件
    toPage({ page, size }) {
      if (page) {
        this.page = page;
      } else if (size) {
        this.perPage = size;
      }
      this.getMediumData();
    },
    dataSearch(index, item) {
      if (!item.keyword) return;
      switch (item.keyword) {
        case 'signed': {
          this.$set(this.paramsObj, 'signDetailStatus', [1, 2, 5, 6]);
          break;
        }
        case 'journal': {
          this.$set(this.paramsObj, 'journalStatus', 1);
          break;
        }
        case 'noJournal': {
          this.$set(this.paramsObj, 'journalStatus', 2);
          break;
        }
        case 'cancelJournal': {
          this.$set(this.paramsObj, 'journalStatus', 3);
          break;
        }
        case 'exclusiveAgency': {
          this.$set(this.paramsObj, 'operateMode', [3]);
          break;
        }
        case 'noExclusiveAgency': {
          this.$set(this.paramsObj, 'operateMode', [4]);
          break;
        }
      }
      this.freshData();
    },
    // 修改备注在列表的显示
    async mutedUpdateMediumList(mediumId) {
      const result = await this.getMediumData(false, true, mediumId);
      if (mediumId && result && result.code === 200 && result.data && result.data.items) {
        for (let i = 0; i < result.data.items.length; i++) {
          const element = result.data.items[i].medium;
          if (element.mediumId === mediumId) {
            this.$refs.mediumListTabel.freshCaseList(element);
            break;
          }
        }
      }
    },
    // 切换平台
    async handleTabClick(key) {
      this.activeTabs = key;
      this.clearPlatform(key);
      this.getSettingData();
      this.crearParams();
      await this.$nextTick();
      if (this.presetFilter && this.$refs.filter) {
        setTimeout(() => {
          this.$refs.filter.presetFilterDefault(this.presetFilter);
        }, 300);
      } else {
        this.getMediumData(true);
      }
    },
    // 若选择的tab不为直播或更多，清空平台选择
    clearPlatform(key) {
      if (!['5', '6'].includes(key)) {
        const index = this.paramsOptions.findIndex(option => option.key === 'pingtai');
        index !== -1 && this.paramsOptions.splice(index, 1);
      }
    },
    // 选中直播/更多
    handleExtendTabsChange(id, value) {
      const index = this.paramsOptions.findIndex(option => option.key === 'pingtai');
      if (index === -1) {
        value && this.paramsOptions.push({ key: 'pingtai', value });
      } else {
        value ? (this.paramsOptions[index].value = value) : this.paramsOptions.splice(index, 1);
      }
      this.handleTabClick(id);
    },
    freshData() {
      this.getMediumData(true);
    },
    editInfoCallBack() {
      // this.getFilter();
      this.getMediumData(false, false);
    },
    crearParams() {
      try {
        if (this.$refs.filter) this.$refs.filter.deleteFilter();
        this.paramsObj = {};
      } catch (error) {
        console.log(error);
      }
    },
    // 已勾选数据
    getResourceSelectedIds() {
      const selectedData = this.$refs['mediumListTabel'] && this.$refs['mediumListTabel'].getSelectedData();
      if (!selectedData) return '';
      return selectedData.filter(i => i.mediumId).map(i => i.mediumId).join(',');
    },
    // 快速发起询单/询价
    quicklyCreate(label, name) {
      const ids = this.getResourceSelectedIds();
      if (!ids) {
        this.$message.warning('请先勾选账号');
        return;
      }
      resourceFilter({ ids }).then(res => {
        if (res.code === 200) {
          if (!res.data.length) return this.$message.warning(`选择入驻飞来通告的账号资源后才可发起${label}`);
          sessionStorage.setItem('inBoundAccountData', JSON.stringify(res.data));
          this.$confirm(`<div>你已选择 ${res.data.length} 个账号资源，是否快速发起${label}</div><div style="color: #999999;font-size: 14px;">注意：未入驻飞来通告的账号资源已被过滤</div>`, '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            iconClass: 'del-icon',
            customClass: 'del-message del-message-cancel',
            dangerouslyUseHTMLString: true,
            center: true,
            type: 'warning'
          }).then(() => {
            const routeUrl = this.$router.resolve({
              name,
              query: {
                fromResource: 1
              }
            });
            window.open(routeUrl.href, '_blank');
          }).catch(() => {
            return false;
          });
        }
      }).catch(err => console.error(err));
    },
    switchFilterOpen() {
      // this.$store.commit('SET_FILTER_OPEN', !this.filterOpen);
      // this.$store.state.medium.filterOpen = true;
      this.$refs.filter.openFilter();
    },
    filterOperate(data, method = '') {
      const filter = this.$refs.filter;
      const easyMethods = ['queryClick', 'queryEmpty', 'deleteFilter'];
      if (easyMethods.includes(method)) {
        filter[method]();
        return;
      }
      switch (method) {
        case 'deleteTag':filter[method](data); break;
        case 'getPresetFilter':filter[method]; break;
        case 'setFilterParams':filter[method](data); break;
      }
    },
    setValueModelResult(res) {
      this.selectValueResult = res || [];
    },
    getPresetFilter() {
      return this.$refs.filter.getPresetFilter;
    },
    getPresetInfo() {
      const presetInfo = {};
      if (this.$refs.filter) return this.$refs.filter.getPresetInfo();
      return presetInfo;
    },
    toCreate(params) {
      this.$refs.resourceCreateRef.openDialog(params);
    }
  }
};
</script>
<style scoped lang="scss">
.medium-container {
  width: 100%;
  ::v-deep {
    .fb-button-group {
      flex-shrink: 0;
    }
  }
  .statistics-box {
    &::v-deep {
      .data-item {
        padding-left: 10px;
        margin-right: 0;
        flex-basis: calc(100% / 6) !important;
      }
      .data-item:first-child {
        padding-left: 0;
      }
      .data-item:nth-of-type(4n) {
        border-right: 1px solid #DDE1EA;
      }
    }
  }
}
.opeator-bar {
  @include flexStyle($align: center);
  align-items: flex-start;
  margin-bottom: 10px;
  .flex-one {
    flex: 1;
  }
  .default-view {
    height: 32px;
    width: 120px;
    border-radius: 4px;
    font-size: 14px;
    border: 1px solid #ddd;
    cursor: pointer;
    .view-name {
      width: 80px;
      justify-content: center;
      padding: 0 4px;
      color: #666;
      &:hover {
        color: #406eff;
      }
    }
    .view-icon {
      border-left: 2px solid #ddd;
      height: 16px;
      width: 40px;
      text-align: center;
    }
  }
}

.mobile-icon {
  @include flexStyle($align: center, $direction: column);
  margin-right: 24px;
  .text {
    font-size: 10px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    color: #aeb6c7;
    line-height: 14px;
    margin-top: 2px;
  }
  .img{
    width: 24px;
    height: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.resource-content {
  background:#fff;
  position: relative;
  padding: 16px 20px 55px 20px;
  margin: 16px 16px 0 16px;
  min-height: calc(100vh - 64px);
  &.mobile-min-height {
    margin: 0;
    padding: 0px 0px 55px 0px;
  }
}
.resource-page-left {
  padding-top: 16px;
  width: 100%;
  background-color: #fff;
  &.filter-open {
    width: calc(100% - 359px);
  }
}
.resource-page-right {
  margin-left: 20px;
  &.mobile-page-right {
    margin-left: 0;
  }
}
.total-container {
  font-size: 12px;
  text-align: left;
  color: #aeb6c7;
  .num {
    font-size: 14px;
    font-family: DIN Alternate, DIN Alternate-Bold;
    font-weight: 700;
    color: #5f77c3;
    margin: 0 3px;
  }
}
</style>
